﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using MQTTClient.Model;
using MQTTClient.Bll;
using MQTTClient.Model.UDPEvent;
using Newtonsoft.Json;

namespace MQTTClient
{
    public partial class UDPClientForm : Form
    {
        private delegate void AddItemToListBoxDelegate(string str);
        private delegate void AddItemToListBoxDelegate2(string str);
        /// <summary>
        /// 客户端列表显示
        /// </summary>
        /// <param name="str"></param>
        private delegate void AddItemToListBoxDelegate3(ClientPayloadDataModel client);
        /// <summary>
        /// 删除掉线的客户端列表显示
        /// </summary>
        /// <param name="str"></param>
        private delegate void DeleteCloseClientDelegate(ClientPayloadDataModel client);
        /// <summary>
        /// 所有聊天消息显示
        /// </summary>
        /// <param name="str"></param>
        private delegate void messageBoxDelegate(string str);
        UDPClientBll UDPClientBll  ;
        public UDPClientForm()
        {
            InitializeComponent();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            UDPClientBll = new UDPClientBll();
            UDPClientBll.ClientProt =int.Parse( textBox3.Text.Trim());
            UDPClientBll.ServerIP = textBox1.Text.Trim();
            UDPClientBll.ServerPort = int.Parse(textBox2.Text.Trim());
            UDPClientBll.ClientId = textBox5.Text.Trim();
            UDPClientBll.ServerConnectdEvent += this.ServerConnectd;
            UDPClientBll.MyExceptionEvent += this.MyException;
            UDPClientBll.SendDatadEvent += this.SendDatadEvent;
            UDPClientBll.ReceivedDataEvent += this.ReceivedDataEvent;

            UDPClientBll.ServerStart();
            SendDataText("","");//发送空数据，显示上线
            button3.Enabled = false;
            button2.Enabled = true;
        }
        public void ServerConnectd(object sender, ServerConnectdEventArgs e)
        {
            AddItemToListBox(e.Message);
        }
        /// <summary>
        /// 数据发送处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void SendDatadEvent(object sender, ClientDataEventArgs e)
        {
             
        }
        /// <summary>
        /// 数据接收处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ReceivedDataEvent(object sender, ClientDataEventArgs e)
        {
            ClientPayloadDataModel cdata = new ClientPayloadDataModel();
            cdata = JsonConvert.DeserializeObject<ClientPayloadDataModel>(e.ClientData);
            if (cdata.ClientList.Count > 0)//服务器发送的，客户列表数据，非聊天数据
            {
                if (cdata.ClientDataType==1) {//客户上线
                foreach (ClientPayloadDataModel client in cdata.ClientList)
                {
                    //if (listBox1.Items.IndexOf(c.SendDataClientName) == -1)
                    //    AddItemToListBox3(c.SendDataClientName);
                    AddItemToListBox3( client);

                    }
                }
                else if (cdata.ClientDataType == 2) {//客户下线

                    DeleteCloseClient(cdata);

                }

            }
            else
            {
                string str = cdata.IsSiLiao ? "[私聊]" : "[公聊]";
                string mesg = str + GetUserNameIsMe(cdata.SendDataClientName)+ "对" + GetUserNameIsMe(cdata.ClientName)+ "说:" + cdata.DataMessage + "--" + cdata.DataMessageTime;
                AddmessageBox(mesg);
            }
            AddItemToListBox("数据接收:" + e.ClientData);
        }
        private string GetUserNameIsMe(string username)
        {
            return username.Equals(UDPClientBll.ClientId) ? "我" : username;
        }
        public void MyException(object sender, MyExceptionEventArgs e)
        {
            AddItemToListBox(e.ExceptionMessage);
        }
        private void button2_Click_1(object sender, EventArgs e)
        {
            UDPClientBll.ServerIP = null;
            UDPClientBll.ClientId = null;
                     
            UDPClientBll.SendDatadEvent -= this.SendDatadEvent;
            UDPClientBll.ReceivedDataEvent -= this.ReceivedDataEvent;
            UDPClientBll.ServerClose();
            //先关闭再退订
            //UDPClientBll.MyExceptionEvent -= this.MyException;
            //UDPClientBll.ServerConnectdEvent -= this.ServerConnectd;
            button3.Enabled = true;
            button2.Enabled = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (button3.Enabled)
            {
                MessageBox.Show("请先连接服务器！");
                return;
            }
            if (!checkBox2.Checked)
            {
                if (textBox7.Text.Trim().Length == 0)
                {
                    MessageBox.Show("请提供接收人姓名");
                    return;
                }
            }
            if (textBox8.Text.Trim().Length == 0)
            {
                MessageBox.Show("请填写发送信息！");
                return;
            }

            string data = textBox8.Text.Trim();
            string username = textBox7.Text.Trim();
            SendDataText(username,data);
        }
        private void SendDataText(string username,string data)
        {
            ClientPayloadDataModel cdata = new ClientPayloadDataModel();
            cdata.SendDataClientName = UDPClientBll.ClientId;
            cdata.ClientName = username.Length==0?"所有人":username;
            cdata.DataMessage = data;
            cdata.DataMessageTime = DateTime.Now.ToString();
            cdata.IsSiLiao = checkBox1.Checked;
            string JsonStr = JsonConvert.SerializeObject(cdata);
            UDPClientBll.BeginSendData(JsonStr);
        }
        private void AddItemToListBox(string str)
        {
            if (richTextBox1.InvokeRequired)
            {
                AddItemToListBoxDelegate d = AddItemToListBox;
                richTextBox1.Invoke(d, str);
            }
            else
            {
                string str2 = richTextBox1.Text.Insert(0, str + "  " + DateTime.Now.ToString() + "\r\n");
                richTextBox1.Text = str2;
            }
        }
        /// <summary>
        /// 客户列表显示
        /// </summary>
        /// <param name="str"></param>
        private void AddItemToListBox3(ClientPayloadDataModel client)
        {
            if (listBox1.InvokeRequired)
            {
                AddItemToListBoxDelegate3 d = AddItemToListBox3;
                listBox1.Invoke(d, client);
            }
            else
            {
                int count = -1;
                for (int i = 0; i < listBox1.Items.Count; i++)
                {
                    if (listBox1.Items[i].ToString().Contains(client.SendDataClientName + "--"))
                    {
                        //count = i;
                        //break;
                        listBox1.Items.RemoveAt(i);
                    }
                }
                if (count == -1)
                {
                    listBox1.Items.Insert(0, client.SendDataClientName + "--" + client.ClinetIpProt);
                }
                //else
                //{
                //    listBox1.Items.RemoveAt(count);
                //    listBox1.Items.Insert(0, client.SendDataClientName + "--" + client.ClinetIpProt);
                //}
                listBox1.Refresh();
            }
        }
        /// <summary>
        /// 删除掉线客户列表显示
        /// </summary>
        /// <param name="str"></param>
        private void DeleteCloseClient(ClientPayloadDataModel client)
        {
            if (listBox1.InvokeRequired)
            {
                DeleteCloseClientDelegate d = DeleteCloseClient;
                listBox1.Invoke(d, client);
            }
            else
            {
                for (int k = 0; k < client.ClientList.Count; k++)//掉线的客户端集合
                {
                    for (int i = 0; i < listBox1.Items.Count; i++)//客户列表中的客户
                    {
                        if (listBox1.Items[i].ToString().Contains(client.ClientList[k].SendDataClientName + "--"))
                        {
                            //count = i;
                            //break;
                            listBox1.Items.RemoveAt(i);
                        }
                    }
                }
                listBox1.Refresh();
            }
        }
        private void AddmessageBox(string str)
        {
            if (messageBox.InvokeRequired)
            {
                messageBoxDelegate d = AddmessageBox;
                messageBox.Invoke(d, str);
            }
            else
            {
                messageBox.AppendText(str + "\r\n");
                messageBox.ScrollToCaret();
            }
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem != null)
            {
                //textBox7.Text = listBox1.SelectedItem.ToString();
                int len = listBox1.SelectedItem.ToString().IndexOf("--");
                textBox7.Text = listBox1.SelectedItem.ToString().Substring(0, len);
            }
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox2.Checked)
            {
                checkBox1.Visible = false;
                textBox7.Visible = false;
                checkBox1.Checked = false;
                textBox7.Text = "";
            }
            else
            {
                checkBox1.Visible = true;
                textBox7.Visible = true;
            }
        }
    }
}
